<template>
    <div class="shop-list">
        <Teleport to=".header">
            <Header :str="keyword"></Header>
        </Teleport>
       <div class="goods-list">
        <div class="goods-list-item">
            <van-card
            v-for="item in goodsList"
            :key="item.proid"
                num="1"
                :price="item.originprice.toFixed(2)"
                :desc="item.desc"
                :title='item.proname'
                :thumb="item.img1 ">
                <template #tags>
                    <van-tag style="margin-right: 5px;" plain type="primary">{{ item.brand }}</van-tag>
                    <van-tag  plain type="primary">{{ item.category }}</van-tag>
                </template>
                <template #footer>
                    <van-button @click="addCartHandler(item.proid)" size="mini">加入购物车</van-button>
                    <van-button @click="goToInfoHandler(item.proid)" size="mini">查看商品详情</van-button>
                </template>
            </van-card>
        </div>
       </div>
    </div>
</template>

<script lang="ts" setup>
import Header from '@/components/header.vue'
import { getSearchList } from '@/apis/goodsList'
import { ref,onMounted } from 'vue';
import { showSuccessToast, showFailToast } from 'vant';
import { addCart } from '@/apis/addCart'
import { useRouter } from 'vue-router';
const $router = useRouter()
//准备一个变量 表示当前关键字
const keyword = ref<string>('电脑')
//准备一个数据，表示商品列表
const goodsList = ref([])
//获取商品列表的数据
const getGoodsList=async()=>{
    const res = await getSearchList(keyword.value)
    console.log(res)
     goodsList.value=res.data
    console.log(goodsList.value)
}

const getKeyword =()=>{
    const list = JSON.parse(window.localStorage.getItem('history') || [])
    if(list[0]) keyword.value=list[0]
    console.log(keyword.value)
   
}
//加入购物车
const addCartHandler=async(proid:string)=>{
    //判断一下登录状态
    const userid = window.localStorage.getItem('user_id')
    if(!userid) {
        showFailToast('请登录')
        return
    }
    //代码来到这里 说明已经可以登录成功了，可以发送请求了
    
     await addCart(userid,proid,'1')
        showSuccessToast('加入购物车成功')
}
//进入详情页面
const goToInfoHandler =(proid:string)=>{
    $router.push( {path:'/detail', query:{proid}})
}
onMounted(()=>{
    getKeyword()
    getGoodsList()
})
</script>

<style lang="scss" scoped>
.goods-list{
     padding: 10px ;
     background-color: #fff;
}
.goods-list-item{
    border: 1px solid #ccc;
    border-radius: 10px;
    overflow: hidden;
    margin-bottom: 10px;
    box-shadow: 1px 1px 10px 2px #ccc;
}
</style>